/**
 * 设置网店名称
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import { Form, Input, Spin, message } from 'antd';
import { layout3 } from '@/utils/config';

import { updateNetworkName } from '../../service';

export default ({ item, visible, handleOk, handleCancel }) => {

  const [ form  ] = Form.useForm();
  const [ loading, setLoading ] = useState(false);

  const onOk = () => {
    if(loading) {
      return false;
    }
    form.validateFields().then(val => {
      handleSubmit(val);
    })
  }

  useEffect(() => {
    if(visible) {
      form.resetFields();
    }
  }, [ visible])


  const handleSubmit = async val => {
    const { name } = val;
    setLoading(true);
    const res = await updateNetworkName({
      id: item.networkId,
      name: name
    })
    if(res.success) {
      message.success('修改成功！')
      handleOk();
      handleCancel();
    }
    let timer = setTimeout(() => {
      setLoading(false);
      clearTimeout(timer);
      timer = null;
    }, 300)
  }

  const onCancel = () => {
    handleCancel();
  }

  return (
    <CommonModal
      title='编辑网点名称'
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Spin spinning={loading}>
        <Form 
          {...layout3}
          name='edit-network-name'
          form={form}
          initialValues={{
            name: item.networkName
          }}
          layout='horizontal' 
        >
          <Form.Item label="网点名称" name="name" rules={[{ required: true, message: '网点名称不能为空' }]}>
            <Input placeholder='请输入网点名称' />
          </Form.Item>
        </Form>
      </Spin>
      
    </CommonModal>
  )
}